<?php


namespace App\Repository\Repositories;


use App\Helpers\Code;
use App\Helpers\Token;
use App\Http\Controllers\Controller;
use App\Http\Serve\Es;
use App\Models\StoreHead;
use App\Models\StoreHeadGoods;
use App\Models\StorePink;
use App\Models\StoreProduct;
use App\Repository\RepositoryInterface\HeadsInterface;
use App\Http\Service\Redisd;

class HeadsRepositories extends Controller implements HeadsInterface
{
    protected $head;
    protected $headGood;

    public function __construct(StoreHead $storeHead,StoreHeadGoods $headGood)
    {
        $this->head = $storeHead;
        $this->headGood = $headGood;
    }

    /**
     * 团长申请
     * @param $params
     * @return array|mixed
     */
    public function applyHead($params)
    {
        try {
            $uid = Token::verifyToken($params['token']);
            $data = [
                'uid'=>$uid,
                'avatar'=>$params['avatar'],
                'name'=>$params['name'],
                'phone'=>$params['phone'],
                'longitude'=>$params['longitude'],
                'latitude'=>$params['latitude'],
                'address'=>$params['address'],
                'status'=>0,
            ];
            $res = $this->head::createHead($data);
            //附近10公里房源id
            $addArea = Redisd::getInstance()->geoadd('area', $res['longitude'], $res['latitude'],$res['id']);
            $es = new Es();
            if (!$es->exists_index('head_list')) {
                //创建es索引，es的索引相当于MySQL的数据库
                $es->create_index('head_list');
            }
            $es->add_doc($res->id,$res,'head_doc','head_list');
            return parent::success("提交成功",$data);
        } catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 团长列表查询
     * @param $param
     * @return array|\Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed
     */
    public function headList($params)
    {
        try {
            if (!empty($params['add_time'])){
                $res = $this->head::search($params['add_time'],$params['end_time']);
                return ['code'=>20000,'msg'=>'查询成功','data'=>$res];
            }
            $data = $this->head->headList();
            return parent::success("查询成功",$data);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 团长状态列表切换
     * @param $status
     * @return array|mixed
     */
    public function headStatus($status)
    {
        try {
            $data = $this->head::headStatus($status);
            return parent::success("查询成功",$data);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 通过/不通过
     * @param $params
     * @return array|mixed
     */
    public function adopt($params)
    {
        try {
            $item = $this->head::headFind($params['id']);
            $res = $this->head::adopt($params['id'],$params['status']);
            $params['status']==1?$status="成功":$status="不通过";
            $sendMsg = (new Code())->getCode($item->phone,"请求已审核","wufen","04945e24cb434763a6053ac369bd42d8");
            if ($sendMsg=="短信发送成功"){
                return parent::success("审核成功",$res);
            }
            return parent::error("短信发送失败");
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 团长管理列表
     * @param $params
     * @return array
     */
    public function adminHeadList($params){
        try {
            if (!empty($params['start_at'])){
                $res = $this->head::search($params['start_at'],$params['end_at'],$params['keyword'],$params['status']);
                return parent::success("查询成功",$res);
            }
            $es = new Es();
            $data = $this->head->headList()->toArray();
            if (!$es->exists_index('head_list')) {
                //创建es索引，es的索引相当于MySQL的数据库
                $es->create_index('head_list');
            }
            foreach ($data['data'] as $v){
                $es->add_doc($v['id'],$v,'head_doc','head_list');
            }
            return ['code'=>20000,'msg'=>'查询成功','data'=>$data];
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }
    /**
     * 团长管理列表es搜索
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function search($params){
        if (!empty($params)){
            $body = [
                'query' => [
                    'match' => [
                        'name' => [
                            'query' => $params
                        ]
                    ]
                ],
                'highlight'=>[
                    'fields'=>[
                        'name'=>[
                            'pre_tags'=>[
                                '<span style="color: red">'
                            ],
                            'post_tags'=>[
                                '</span>'
                            ]
                        ]
                    ]
                ]
            ];
            //调用es的搜索
            $res = (new Es())->search_doc('head_doc','head_list',$body);
            $data = array_column($res['hits']['hits'], '_source');
            foreach ($data as $key=>&$v){
                $v['name'] = $res['hits']['hits'][$key]['highlight']['name'][0];
            }
            unset($v);
            return parent::success("查询成功",$data);
        }
    }

    /**
     * 团长修改
     * @param $params
     * @return array
     */
    public function adminUpdateHead($params){
        try {
            $res = $this->head::updateHead($params);
            $es = new Es();
            if (empty($es->exists_index('head_list'))) {
                $es->create_index('head_list');
            }
            $es->update_doc($params['id'],'head_doc','head_list',['doc'=>$params]);
            return parent::success("修改成功",$res);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 团长推荐
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function recommendHead($params){
        try {
            $search_data = Redisd::getInstance()->geoRadius('area', $params['longitude'], $params['latitude'], 5, 'km', ['ASC']);
            foreach ($search_data as $key => $val) {
                $res = $this->head->headFind($val)->toarray();
                if (!empty($res)) {
                    $near_head[$key] = $res;
                }
            }
            return parent::success("查询成功",$near_head);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }
    /**
     * @param $uid
     * @return \Illuminate\Http\JsonResponse|void
     * 团长申请
     */
    public function findGroupData($uid){
        //参数判断
        if (!is_numeric($uid) || $uid == '') {
            return parent::error('参数格式不正确', '');
        }
        try {
            $groupData = $this->head->where("uid",$uid)->first();
            if(!empty($groupData)){
                if($groupData->status == 0){
                    return parent::success("已申请，审核中",true);
                }elseif($groupData->status == 1){
                    return parent::success("已审核通过",true);
                }else{
                    return parent::success("审核未通过",true);
                }
            }
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * @param $token
     * @return \Illuminate\Http\JsonResponse
     * 团长路线
     */
    public function groupPath($token){
        $uid = Token::verifyToken($token);
        try {
            $address = $this->head->where("uid",$uid)->first("address");
            return parent::success("团长所在地址",$address);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * zyy
     * @param $groupAddPath
     * @return \Illuminate\Http\JsonResponse
     * 路线添加
     */
    public function createGroupPath($groupAddPath){
        try {
            $address = $this->head->where("uid",$groupAddPath['uid'])->first("address")->toArray();
            $addressNew = $address['address'].','.$groupAddPath['addressData'];
            $addressNewData = $this->head->where("uid",$groupAddPath['uid'])->update(['address'=>$addressNew]);
            return parent::success("团长位置添加",$addressNewData);
        }catch (\Exception$exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * zyy
     * @param $token
     * @return \Illuminate\Http\JsonResponse
     * 团长限售商品
     */
    public function groupGoods($token){
        $hid = Token::verifyToken($token);
        try {
            $groupGoodsData = StoreHeadGoods::groupData($hid)->toArray();
            $headGoodData = $this->headGood->with("groupCidData")->where("hid","100")->get()->toArray();
            return parent::success("团长限售商品",$headGoodData);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * @param $groupSetData
     * @return \Illuminate\Http\JsonResponse|void
     * 团长设置团
     */
    public function groupSetting($groupSetData){
        try {
            $GrouwpNewSetting = StorePink::groupSetting($groupSetData);
            return parent::success("团长设置成功",$GrouwpNewSetting);
        }catch (\Exception$exception){
            return parent::error($exception->getMessage());
        }
    }
}
